﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lizk.Media
{
    public class AnimeScanner : TypeScanner
    {
        public AnimeScanner(string type) : base(type) { }

        public override void Scan(string rootPath, Predicate<VideoData> exists, Action<VideoData> mediaAdded)
        {

            string type, group, show, image, format;
            string volumeLabel = new DriveInfo(rootPath).VolumeLabel;
            string rootPathString = rootPath.EndsWith(Path.DirectorySeparatorChar.ToString()) ? rootPath : rootPath + Path.DirectorySeparatorChar;
            List<string> showDirs = new List<string>();

            foreach (string groupDir in Directory.GetDirectories(Path.Combine(rootPath, this.Type)))
            {
                group = Path.GetFileName(groupDir);
                if (group.StartsWith(".") || group.StartsWith("_"))
                    continue;

                // If group dir available
                if (group.StartsWith("#"))
                    showDirs.AddRange(Directory.GetDirectories(groupDir));
                else
                    showDirs.Add(groupDir);
            }

            foreach (string showDir in showDirs)
            {
                show = Path.GetFileName(showDir);
                if (show.StartsWith(".") || show.StartsWith("_"))
                    continue;

                group = Path.GetFileName(Path.GetDirectoryName(showDir));

                image = MediaUtil.FindImage(showDir, PictureExtensions);
                if (image != null)
                    image = image.Replace(rootPathString, "");

                foreach (string file in Directory.GetFiles(showDir, "*", SearchOption.AllDirectories))
                {
                    if ((format = GetVideoType(Path.GetFileName(file))) == null)
                        continue;

                    VideoData v = new VideoData();
                    v.path = file.Replace(rootPathString, ""); ;
                    v.volume = volumeLabel;


                    if (exists == null || !exists(v))
                    {
                        FileInfo f = new FileInfo(file);
                        if (format == "media")
                            VideoData.ParseAnimeFilename(v, file);

                        v.season = 1;
                        v.mimetype = MediaUtil.GetMimeType(f.Extension.Substring(1));
                        v.filesize = f.Length;
                        v.show = show;
                        v.type = Type;
                        v.lastmodified = f.CreationTime.ToFileTime();
                        v.format = format;
                        v.artwork = image != null ? image : "";

                        //v.source = type.Substring(0, type.Length - 1);

                        mediaAdded(v);
                    }
                }
            }
        }
    }
}
